package com.tianci.appstore.controller;

import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.os.RemoteException;

import com.coocaa.app.gamecenter.pages.home.GameMainActivity;
import com.coocaa.framework.AppStoreApplication;
import com.coocaa.launcher.EasyLauncherActivity;
import com.coocaa.x.app.framework.app.LiteAppApplication;
import com.coocaa.x.app.framework.app.LiteAppApplication.ContentAppChangedReceiver.ContentAppChangedReceiverListener;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.app.CoocaaApplication.PackageReceiver.InstallUninstallInterface;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.LiteURI;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.framework.utils.Storage;
import com.coocaa.x.framework.utils.Storage.IStorageListener;
import com.coocaa.x.framework.utils.Storage.SDevice;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litecontent.LiteContentServiceConnecter;
import com.coocaa.x.service.litecontent.data.apps.com_coocaa_app.AppData;
import com.coocaa.x.service.litecontent.data.apps.com_coocaa_app.AppUpdateBean;
import com.coocaa.x.service.litecontent.data.apps.com_coocaa_app.RP_Installed_Apps;
import com.coocaa.x.service.litecontent.data.apps.com_coocaa_app.RP_Update_Apps;
import com.coocaa.x.service.litedownloader.data.TaskInfo;
import com.coocaa.x.service.litepm.data.AppInfo;
import com.coocaa.x.service.litepm.data.MActivityInfo;
import com.skyworth.framework.skysdk.android.SkySystemUtil;
import com.skyworth.framework.skysdk.properties.SkyGeneralProperties;
import com.skyworth.framework.skysdk.util.SdCardChecker;
import com.skyworth.logsdk.appstore.LogAPIForAppStore;
import com.skyworth.webSDK.webservice.tcappstore.AppMainPageData;
import com.skyworth.webSDK.webservice.tcappstore.AppMainPagebeans;
import com.skyworth.webSDK.webservice.tcappstore.AppMainSubSorts;
import com.skyworth.webSDK.webservice.tcappstore.AppStoreException;
import com.tianci.appstore.AppStoreActivity;
import com.tianci.appstore.R;
import com.tianci.appstore.database.AppStoreDB;
import com.tianci.appstore.dataprovider.AppDataProvider;
import com.tianci.appstore.ui.data.SkyAppBaseData;
import com.tianci.appstore.ui.data.SkyAppDetailData.AppStatus;
import com.tianci.appstore.ui.data.SkyCategoryData;
import com.tianci.appstore.ui.data.SkyListAppData;
import com.tianci.appstore.ui.data.SkyListAppData.ListType;
import com.tianci.appstore.ui.data.SkyMainAppData;
import com.tianci.appstore.ui.data.SkyManageBlockData;
import com.tianci.appstore.ui.data.SkySndCgyData;
import com.tianci.appstore.ui.list.locallist.LocalListDataListener;
import com.tianci.appstore.ui.mainpage.OnCategoryRefreshListener;
import com.tianci.appstore.ui.mainpage.OnContentRefreshListener;
import com.tianci.appstore.ui.mainpage.OnMainPageControlListener;
import com.tianci.appstore.utils.AsyncTask;
import com.tianci.appstore.utils.SkyConstants;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class AppStoreMainPageController extends AppStoreBaseController implements
        OnMainPageControlListener, InstallUninstallInterface, IStorageListener,
        ContentAppChangedReceiverListener {
    private static final String tag = "test";
    private static final String STOREPACKAGE = "com.tianci.appstore";
    private Context mContext = null;
    private static AppStoreMainPageController mainPageController = null;
    private OnContentRefreshListener mContentListener = null;
    private LocalListDataListener moreDataListener = null;
    private List<AppMainPageData> mainPageList = null;
    // private List<SkyCategoryData> firstSortList = null;
    private List<SkyAppBaseData> managerList = null;

    private HashSet<SkyCategoryData> mHashRefresh = new HashSet<SkyCategoryData>();
    public static boolean myAppLoaded = false;
    public static final String GUANLI = "1000";
    public static final String MINE = "1001";
    private boolean mLocalData = false;
    private int updateCount = 0;
    private int downloadCount = 0;
    public static AppStoreMainPageController getInstance(Context c) {
        if (null == mainPageController) {
            mainPageController = new AppStoreMainPageController(c);
        }
        return mainPageController;
    }

    public AppStoreMainPageController(Context c) {
        mContext = c;
        mainPageList = new ArrayList<AppMainPageData>();
        managerList = new ArrayList<SkyAppBaseData>();
    }

    public void init() {
        CoocaaApplication.addPackageListener(this);
        Storage.addListener(this);
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                getMainPageDataFromeWeb();

                LiteAppApplication
                        .addContentAppChangedReceiverListener(AppStoreMainPageController.this);
                AppStoreBaseController.addUpdateDownloadCountHandler(mUpdateDownloadCountHandler);
            }
        }).start();
    }

    public void setRefreshMainPageListener(OnContentRefreshListener listener,
                                           List<SkyCategoryData> list) {
        this.mContentListener = listener;
        refreshContent(list);
    }

    public void setLocalListDataListener(LocalListDataListener listener) {
        moreDataListener = listener;
    }

    public List<AppMainPageData> getMainPageDataList() {
        return mainPageList;
    }

    public UpdateDownloadCountHandler mUpdateDownloadCountHandler = new UpdateDownloadCountHandler() {

        @Override
        public void updateDownloadCount(int count) {
            // TODO Auto-generated method stub
            LogUtils.d("test", "updateDownloadCount---count has change:" + count);
            if (mContentListener != null)
                refreshDownloadBlock(count);
//                refreshGLContent(GUANLI);

        }

    };

    private void refreshContent(final List<SkyCategoryData> list) {
        // List<SkyCategoryData> list = new ArrayList<SkyCategoryData>();
        // list.addAll(firstSortList);
        LogUtils.d(tag, "refreshContent--list size--" + list.size());
        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean delay = false;
                int pos = 0;
                for (final SkyCategoryData category : list) {
                    LogUtils.d(tag, "getCategoryContent----" + category.id + " "
                            + (mainPageList != null));
                    AppStoreActivity.dismisWelcome = true;
                    if (delay && pos > 1) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    pos++;
                    delay = true;
                    if (category.id.equals(GUANLI)) {
                        LogUtils.d(tag, "getCategoryContent--manager!!!!!--");
                        updateManagerData(category);
                        continue;
                    } else if (category.id.equals(MINE)) {
                        LogUtils.d("localapp", "getCategoryContent--MINE*****--" + myAppLoaded);
                        if (myAppLoaded && list.size() > 2) // 我的已经refresh过了，不需要再刷新
                        {
                            LogUtils.d(tag, "getCategoryContent--MINE--aaa");
                            myAppLoaded = false;
                            continue;
                        }
                        List<AppInfo> appList = getInstalledApps();

                        LogUtils.d("localapp", "refreshMainContent size:" + appList.size());
                        List<SkyAppBaseData> myAppList = formData(appList);
                        LogUtils.d(tag, "getCategoryContent--MINE*****--size:");
                        mContentListener.refreshContent(myAppList, category);
                        refreshMyAppCorner(myAppList);
                        continue;
                    }

                    if (!AppStoreBaseController.NETSTATUS) {
                        List<SkyAppBaseData> appDataLists = AppStoreDB.getInstance()
                                .getMainPageDataFromDB(category);
                        LogUtils.d(tag, "getCategoryContent--isNetOK:false--");
                        mContentListener.refreshContent(appDataLists, category);
                        for (SkyAppBaseData data : appDataLists) {
                            String pkgtemp = data.getPackageName();
                            if (pkgtemp != null && !pkgtemp.equals("")) {
                                AppStatus status = AppStatus.NOT_DOWNLOADED;
                                status = AppDataProvider.getInstance().isAppInstalled(pkgtemp);
                                refreshStatus(pkgtemp, status);
                            }
                        }
                        continue;
                    }

                    if (mainPageList != null && mainPageList.size() > 0) {
                        List<SkyAppBaseData> appDataLists = getAppDataList(category);
                        LogUtils.d(tag, "getCategoryContent--(appDataLists != null)--"
                                + (appDataLists != null));
                        mContentListener.refreshContent(appDataLists, category);
                        for (SkyAppBaseData data : appDataLists) {
                            String pkgtemp = data.getPackageName();
                            if (pkgtemp != null && !pkgtemp.equals("")) {
                                AppStatus status = AppStatus.NOT_DOWNLOADED;
                                status = AppDataProvider.getInstance().isAppInstalled(pkgtemp);
                                refreshStatus(pkgtemp, status);
                            }
                        }
                        continue;
                    } else {
                        LogUtils.d("test", "running this line");
                        if (mLocalData) {
                            List<SkyAppBaseData> appDataLists = AppStoreDB.getInstance()
                                    .getMainPageDataFromDB(category);
                            LogUtils.d("db", "getCategoryContent--time >= 10000--" + appDataLists.size());
                            mContentListener.refreshContent(appDataLists, category);
                            for (SkyAppBaseData data : appDataLists) {
                                String pkgtemp = data.getPackageName();
                                if (pkgtemp != null && !pkgtemp.equals("")) {
                                    AppStatus status = AppStatus.NOT_DOWNLOADED;
                                    status = AppDataProvider.getInstance().isAppInstalled(pkgtemp);
                                    refreshStatus(pkgtemp, status);
                                }
                            }
                            continue;
                        }
                    }
                }
            }
        }).start();

    }

    private void refreshMyAppCorner(final List<SkyAppBaseData> myappList){
        AsyncTask.runOnThread(new Runnable() {
            @Override
            public void run() {
                refreshMyApp(getMyAppCornerData(false), myappList);
            }
        });
    }

    public List<SkyAppBaseData> fixMainData(List<SkyAppBaseData> appDataLists) {
        if (appDataLists == null)
            return null;
        // LogUtils.d("app", "fixMainData " + appDataLists.size());
        if (appDataLists.size() < 13) {
            return appDataLists;
        } else {
            appDataLists = appDataLists.subList(0, 11);
            SkyListAppData d = new SkyListAppData(ListType.LOCAL_APP_LIST, "more",
                    getString(R.string.more), "", "");
            appDataLists.add(11, d);
            return appDataLists;
        }
    }

    public void showMoreAppData() {
        // List<SkyAppBaseData> appDataLists = AppDataProvider.getInstance().getLocalData()
        // .getLocalAppsForMainPage();
        // appDataLists = appDataLists.subList(11, appDataLists.size());
        // LogUtils.d("app", "showMoreAppData: " + appDataLists.size());
        // List<SkyListAppData> list = new ArrayList<SkyListAppData>();
        // for (int i = 0; i < appDataLists.size(); i++)
        // {
        // SkyListAppData appInfo = (SkyListAppData) appDataLists.get(i);
        // list.add(appInfo);
        // }
        // LogUtils.d("app", "showMoreAppData222: " + list.size());
        // moreDataListener.onLocalListLoaded(list);
    }

    // 获取主页数据
    private void getMainPageDataFromeWeb() {
        // new Thread()
        // {
        //
        // @Override
        // public void run()
        // {
        // TODO Auto-generated method stub
        try {
            mainPageList = CoocaaApplication.getCoocaaWebService().getAppStoreService().getMainPageData("{ver:2}");
//             mainPageList = CoocaaApplication.getCoocaaWebService().getAppStoreService().getMainPageData();
        } catch (AppStoreException e) {
            // TODO Auto-generated catch block
            LogAPIForAppStore.reportInterfaceError("获取应用圈首页数据", Android.throwable2String(e));
            e.printStackTrace();
        }
        if (mainPageList != null) {
            LogUtils.d(tag, "getMainPageDataFromeWeb!!! the mainpage size is " + mainPageList.size());
//            if (mainPageList.size() < 1)
//                AppStoreApplication.needKillApplication = true;
        } else
        {
            LogUtils.d(tag, "getMainPageDataFromeWeb!!!    the mainpage  is null");
        }
        AppStoreDB.getInstance().addMainPageData(mainPageList);
        // }
        //
        // }.start();
    }

    public synchronized List<SkyAppBaseData> getManagerData() {
        synchronized (managerList) {
            if (managerList != null && managerList.size() > 0) {
                return managerList;
            }
            boolean isTianciSystem = false;
            try {
                // while(coocaaApi == null)
                // {
                // LogUtils.d(tag, "coocaaApi == null....");
                // Thread.currentThread().sleep(1);
                // }
                // isTianciSystem = coocaaApi.isCoocaaSystem();
                isTianciSystem = CoocaaApplication.isRoot();
                LogUtils.d(tag, "getManagerData  isTianciSystem" + isTianciSystem);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                LogUtils.d(tag, "getManagerData  error  !!!!");
                e.printStackTrace();
            }
            final SkyAppBaseData updateData = new SkyManageBlockData(
                    SkyManageBlockData.ManagerBlock.UPDATE.toString(),
                    getString(R.string.main_update), "update");
            final SkyAppBaseData downloadData = new SkyManageBlockData(
                    SkyManageBlockData.ManagerBlock.DOWNLOAD.toString(),
                    getString(R.string.main_download), "manage");
            SkyAppBaseData deleteData = new SkyManageBlockData(
                    SkyManageBlockData.ManagerBlock.DELETE.toString(),
                    getString(R.string.main_uninstall), "uninstall");
            SkyAppBaseData speedData = new SkyManageBlockData(
                    SkyManageBlockData.ManagerBlock.SPEED.toString(),
                    getString(R.string.main_speed), "speed");
            SkyAppBaseData scanData = new SkyManageBlockData(
                    SkyManageBlockData.ManagerBlock.SCAN.toString(),
                    getString(R.string.main_scan), "scan");
            SkyAppBaseData aboutData = new SkyManageBlockData(
                    SkyManageBlockData.ManagerBlock.ABOUT.toString(),
                    getString(R.string.main_about), "about");
            SkyAppBaseData remote = new SkyManageBlockData(
                    SkyManageBlockData.ManagerBlock.REMOTE_INSTALL.toString(),
                    getString(R.string.main_remote_install),"remote_install");
            SkyAppBaseData more = new SkyManageBlockData(
                    SkyManageBlockData.ManagerBlock.MORE.toString(),
                    getString(R.string.main_more),"more");
            managerList.add(updateData);
            managerList.add(downloadData);
            managerList.add(deleteData);
            //如果是内测版本则打开u盘安装及远程安装功能，不受后台对破解版开关的控制
            boolean crack = false;
            if ("SkyFans".equals(CoocaaApplication.getContentChannel())){
                crack = true;
            }
            if (crack || SkySystemUtil.isBetaVersion()) {
                managerList.add(scanData);
                managerList.add(remote);
            }
            managerList.add(speedData);
            if (isTianciSystem) { // 判断是否是我们的设备
                SkyAppBaseData moveData = new SkyManageBlockData(
                        SkyManageBlockData.ManagerBlock.MOVE.toString(),
                        getString(R.string.main_move), "move");
                SkyAppBaseData cleanupData = new SkyManageBlockData(
                        SkyManageBlockData.ManagerBlock.CLEAN.toString(),
                        getString(R.string.main_clear), "clear");
                SkyAppBaseData autostartData = new SkyManageBlockData(
                        SkyManageBlockData.ManagerBlock.AUTOSTART.toString(),
                        getString(R.string.main_autostart), "autostart");
//                if (!SkyGeneralProperties.getBoolProperty("NEW_BOOT_FLOW")){
//                    autostartData = new SkyManageBlockData(
//                            SkyManageBlockData.ManagerBlock.AUTOSTART.toString(),
//                            getString(R.string.main_autostart), "autostart");
//                }else{
//                    autostartData = new SkyManageBlockData(
//                            SkyManageBlockData.ManagerBlock.AUTOSTART.toString(),
//                            getString(R.string.main_system_optimization), "autostart");
//                }
                LogUtils.d("test",
                        "getManagerData---SdCardChecker.isSDCardAvaiable():"
                                + SdCardChecker.isSDCardAvaiable());

                if (SdCardChecker.isSDCardAvaiable() && !Environment.isExternalStorageEmulated()) // 只有sdcard存在的情况下才有这么个功能
                {
                    LogUtils.d("test", "getManagerData------isSDEmulated:" + false);
                    //如果是内测版本则打开u盘安装及远程安装功能，不受后台对破解版开关的控制
                    if (crack || SkySystemUtil.isBetaVersion()){
                        managerList.add(autostartData);
                        managerList.add(more);
                        managerList.add(aboutData);
                        managerList.add(cleanupData);
                        managerList.add(moveData);
                    }else{
                        managerList.add(autostartData);
                        managerList.add(cleanupData);
                        managerList.add(moveData);
                        managerList.add(aboutData);
                    }
                }else{
                    managerList.add(autostartData);
                    managerList.add(cleanupData);
                    managerList.add(aboutData);
                }
            }else{
                managerList.add(aboutData);
            }
            return managerList;
        }
    }

    private List<AppUpdateBean> getUpdateBeans(boolean isCache, String pkg, String needAll) {
        LogUtils.d(tag, "getUpdateBeans !!!!!!!!!!!!!isCache:" + isCache);
        List<AppUpdateBean> appdatas = null;
        LiteURI uri = LiteURI.create("apps://com.coocaa.app/update_apps");
        if (!isCache)
            uri.addParams("action", "web");
        if (pkg != null && !pkg.equals("")) {
            uri.addParams("pkg", pkg);
            uri.addParams("needall", needAll);
        }
        String json = null;
        try {
            json = LiteContentServiceConnecter.getService().call(uri.toString());
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        LogUtils.d(tag, "getUpdateBeans !!!!!!!!!!!!! json:" + json);
        if (json != null) {
            RP_Update_Apps rp = RP_Installed_Apps.parseJObject(json, RP_Update_Apps.class);
            appdatas = rp.resource.resource_items;
        }
        if (appdatas == null)
            appdatas = new ArrayList<AppUpdateBean>();
        return appdatas;
    }


    private List<AppUpdateBean> getMyAppCornerData(boolean isCache) {
        List<AppUpdateBean> appdatas = null;
        LiteURI uri = LiteURI.create("apps://com.coocaa.app/update_apps");
        if (!isCache)
            uri.addParams("action", "web");
        uri.addParams("iscompire","iscompire");
        String json = null;
        try {
            json = LiteContentServiceConnecter.getService().call(uri.toString());
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (json != null) {
            RP_Update_Apps rp = RP_Installed_Apps.parseJObject(json, RP_Update_Apps.class);
            appdatas = rp.resource.resource_items;
        }
        if (appdatas == null)
            appdatas = new ArrayList<AppUpdateBean>();
        return appdatas;
    }

    private void refreshMyApp(List<AppUpdateBean> appdatas,List<SkyAppBaseData> myAppList){
        if (myAppList != null && myAppList.size() > 0 && appdatas.size() > 0){
            for (SkyAppBaseData data : myAppList){
                for (AppUpdateBean bean : appdatas){
                    if (bean.bean.isSubscript && data.getPackageName().equals(bean.bean.packagename)){
                        ((SkyListAppData)data).updateBean = bean.bean;
                        mContentListener.refreshMyAppCorner(((SkyListAppData)data));
                        LogUtils.i("corner","refresh app corner " + data.getTitle());
                    }
                }
            }
        }
    }


    private synchronized void updateManagerData(final SkyCategoryData category) {
        LogUtils.d(tag, "updateManagerData-----------" + managerList.size());
        if (managerList.size() < 1) {
            getManagerData();
        }
        try {
            if (mContentListener == null)
                return;
            mContentListener.refreshContent(managerList, category);
            SkyManageBlockData downloadBlock = getManageBlockDataById(SkyManageBlockData.ManagerBlock.DOWNLOAD.toString());
            if (downloadBlock != null) {
                int process = XServiceManager.getDownloaderService()
                        .getTaskListByState(TaskInfo.TASK_STATE.PROCESSING.toString()).size();
                int ready = XServiceManager.getDownloaderService()
                        .getTaskListByState(TaskInfo.TASK_STATE.READY.toString()).size();
                int prepared = XServiceManager.getDownloaderService()
                        .getTaskListByState(TaskInfo.TASK_STATE.PREPARED.toString()).size();
                downloadCount = process + ready + prepared;
                downloadBlock.setUpdateCount(downloadCount);
            }
            SkyManageBlockData updateBlock = getManageBlockDataById(SkyManageBlockData.ManagerBlock.UPDATE.toString());
            if (updateBlock != null) {
                updateCount = getUpdateBeans(false, null, null).size();
                updateBlock.setUpdateCount(updateCount);
            }
            LogUtils.d("appstore", "getManagerData----------update----download----" + updateCount + " "
                    + downloadCount);
            mContentListener.refreshContent(managerList, category);
            LogUtils.d("updatecount is " + (updateCount + downloadCount));
            mContentListener.refreshCategoryRed(category, updateCount + downloadCount);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void refreshUpdateBlock(String pkg) {
        SkyManageBlockData updateBlock = getManageBlockDataById(SkyManageBlockData.ManagerBlock.UPDATE.toString());
        if (updateBlock != null) {
            updateCount = getUpdateBeans(true, pkg, "true").size();
            updateBlock.setUpdateCount(updateCount);
            LogUtils.d("test", "refreshUpdateBlock----------update----" + updateCount);
            if (mContentListener != null) {
                mContentListener.refreshContent(managerList, getCategoryData(GUANLI));
                mContentListener.refreshCategoryRed(getCategoryData(GUANLI), updateCount + downloadCount);
            }
        }
    }

    private void refreshDownloadBlock(int count) {
        downloadCount = count;
        SkyManageBlockData downloadBlock = getManageBlockDataById(SkyManageBlockData.ManagerBlock.DOWNLOAD.toString());
        if (downloadBlock != null) {
            downloadBlock.setUpdateCount(downloadCount);
            LogUtils.d("test", "refreshDownloadBlock----------downloadCount----" + downloadCount);
            if (mContentListener != null) {
                mContentListener.refreshContent(managerList, getCategoryData(GUANLI));
                mContentListener.refreshCategoryRed(getCategoryData(GUANLI), updateCount + downloadCount);
            }
        }
    }

    private SkyManageBlockData getManageBlockDataById(String id) {
        if (managerList.size() < 1) {
            getManagerData();
        }
        for (SkyAppBaseData data : managerList) {
            if (data.getId().equals(id))
                return (SkyManageBlockData) data;
        }
        return null;
    }

    public List<SkyAppBaseData> getAppDataList(SkyCategoryData category) {
        // if (appDataMap != null && appDataMap.size() > 0) { //不要缓存，不然一直有右上角红点
        // if (appDataMap.get(category.id) != null) {
        // LogUtils.d(tag, "getAppDataList---get  from  map --" + category.id);
        // return appDataMap.get(category.id);
        // }
        // }
        List<SkyAppBaseData> appDataList = new ArrayList<SkyAppBaseData>();
        for (int i = 0; i < mainPageList.size(); i++) {
            if (mainPageList.get(i).sortId.equals(category.id)) {
                LogUtils.d(tag, "getAppDataList---sortId--" + mainPageList.get(i).sortId);
                // String sortId = mainPageList.get(i).sortId;
                // String sortName = mainPageList.get(i).sortName;
                List<AppMainSubSorts> subSort = mainPageList.get(i).subSorts;
                for (int j = 0; j < subSort.size(); j++) {
                    // System.out.println("---&&&"+subSort.get(j).sortName);
                    String subSortId = subSort.get(j).sortId;
                    String subSortName = subSort.get(j).sortName;
                    String background = subSort.get(j).flag.toString();
                    String iconUrl = subSort.get(j).imgurl;
                    if (j < SkyConstants.SUBSORTCOUNT) {
                        SkyAppBaseData appData = new SkySndCgyData(subSortId, subSortName, iconUrl,
                                background);
                        int showCount = AppStoreAppListController.getInstance()
                                .showSortAppCount(subSortId);
                        LogUtils.d("count", "getAppDataList--- showCount:" + showCount);
                        ((SkySndCgyData) appData).setCount(showCount);
                        appDataList.add(appData);
                    }
                }
                if (subSort.size() < SkyConstants.SUBSORTCOUNT) {
                    for (int m = 0; m < SkyConstants.SUBSORTCOUNT - subSort.size(); m++) {
                        SkyAppBaseData appData = new SkySndCgyData("1000" + m, "备用" + m, "", "");
                        ((SkySndCgyData) appData).setCount(0);
                        appDataList.add(appData);
                    }
                }
                List<SkyAppBaseData> tempList = new ArrayList<SkyAppBaseData>();
                List<AppMainPagebeans> pageBeans = mainPageList.get(i).apps;
                for (int k = 0; k < pageBeans.size(); k++) {
                    // System.out.println("---***"+pageBeans.get(k).name);
                    String appId = pageBeans.get(k).appid;
                    String appIcon = pageBeans.get(k).icon;
                    String appName = pageBeans.get(k).name;
                    String pkg = pageBeans.get(k).packageName;
                    String adpic = pageBeans.get(k).adpic;
                    String cornerIcon = pageBeans.get(k).superscript;
                    String type = pageBeans.get(k).apptype;
                    //  LogUtils.d(tag,"getAppDataList  appName:"+appName+" pkg:"+pkg);
                    SkyAppBaseData appData = new SkyMainAppData(appId, appName, appIcon, adpic,
                            cornerIcon, type);
                    appData.setPackageName(pkg);
                    AppStatus status = AppStatus.NOT_DOWNLOADED;
                    status = AppDataProvider.getInstance().isAppInstalled(pkg);
                    if(status == AppStatus.INSTALLED)
                        tempList.add(appData);
                    else
                        appDataList.add(appData);
                }

                int size = appDataList.size();
                LogUtils.d(tag,"getAppDataList appDataList  size:"+size);
                if(size < 12)
                {
                    int n = (12 - size) >= tempList.size() ? tempList.size():(12 - size);
                    LogUtils.d(tag,"getAppDataList n:"+n);
                    for(int m = 0; m < n; m ++)
                    {
                        appDataList.add(tempList.get(m));
                    }
                }
            }
        }
        // appDataMap.put(category.id, appDataList);
        return appDataList;
    }

    public List<SkyCategoryData> getMainCategoryList() {
        // firstSortList.clear();
        // firstSortList.add(new SkyCategoryData(MINE, getString(R.string.main_mine)));
        // for (int i = 0; i < mainPageList.size(); i++)
        // {
        // SkyCategoryData c = new SkyCategoryData(mainPageList.get(i).sortId,
        // mainPageList.get(i).sortName);
        // firstSortList.add(c);
        // }
        // firstSortList.add(new SkyCategoryData(GUANLI, getString(R.string.main_manager)));
        // return firstSortList;
        List<SkyCategoryData> firstSortList = new ArrayList<SkyCategoryData>();
        firstSortList.add(new SkyCategoryData(MINE, getString(R.string.main_mine)));
        for (int i = 0; i < mainPageList.size(); i++) {
            SkyCategoryData c = new SkyCategoryData(mainPageList.get(i).sortId,
                    mainPageList.get(i).sortName);
            firstSortList.add(c);
        }
        firstSortList.add(new SkyCategoryData(GUANLI, getString(R.string.main_manager)));
        return firstSortList;
    }

    private void refreshGLContent(final String id) {
        LogUtils.d(tag, "refreshGLContent----");
        runOnThread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                updateManagerData(getCategoryData(id));
//                if (updateCount + downloadCount >= 0)
//                {
//                    runOnUiThread(new Runnable()
//                    {
//                        public void run()
//                        {
//                            if (mContentListener != null)
//                            {
//                                mContentListener.refreshCategoryRed(getCategoryData(id),
//                                        updateCount + downloadCount);
//                            }
//                        }
//                    });
//                }
            }
        });
    }


    private List<SkyAppBaseData> formData(List<AppInfo> list) {
        List<SkyAppBaseData> ret = new ArrayList<SkyAppBaseData>();
        boolean isLauncherShow = true;
        boolean isGameShow = true;
        String launcher_entry = SkyGeneralProperties.getProperty("x_launcher_entry");
        if (launcher_entry != null) {
            isLauncherShow = Boolean.parseBoolean(launcher_entry);
        } else {
            isLauncherShow = true;
        }
        String gamecenter_entry = SkyGeneralProperties.getProperty("x_gamecenter_entry");
        if (gamecenter_entry != null) {
            isGameShow = Boolean.parseBoolean(gamecenter_entry);
        } else {
            isGameShow = true;
        }
        LogUtils.d("show", "isLauncherShow:" + isLauncherShow + " isGameShow:" + isGameShow);
        if (list != null && list.size() > 0) {
            synchronized (list) {
                for (AppInfo info : list) {
                    if (info.activityList != null && info.activityList.size() > 1) {
                        List<MActivityInfo> mList = info.activityList;
                        for (MActivityInfo aInfo : mList) {
                            SkyListAppData appInfo = new SkyListAppData(ListType.LOCAL_APP_LIST,
                                    "", aInfo.name, "", info.pkgName);
                            appInfo.setVersionName(String.valueOf(info.versionCode));
                            appInfo.setInstallTime(info.firstInstallTime);
                            appInfo.setMainActivity(aInfo.className);
                            appInfo.setPackageName(info.pkgName);
                            if (!aInfo.className.equals(AppStoreActivity.class.getName())) {
                                if (aInfo.className.equals(EasyLauncherActivity.class.getName())) {
                                    if (isLauncherShow)
                                        ret.add(0, appInfo);
                                } else if (aInfo.className.equals(GameMainActivity.class.getName())) {
                                    if (isGameShow) {
                                        if (ret.size() == 0) {
                                            ret.add(0, appInfo);
                                        } else {
                                            boolean contain_game = false;
                                            for (SkyAppBaseData data : ret) {
                                                String pkg = ((SkyListAppData) data).getPkgName();
                                                if (pkg.contains(STOREPACKAGE)) {
                                                    contain_game = true;
                                                }
                                            }
                                            if (contain_game)
                                                ret.add(1, appInfo);
                                            else
                                                ret.add(0, appInfo);
                                        }
                                    }
                                } else
                                    ret.add(appInfo);
                            }
                        }
                    } else {
                        SkyListAppData appInfo = new SkyListAppData(ListType.LOCAL_APP_LIST, "",
                                info.appName, "", info.pkgName);
                        appInfo.setVersionName(String.valueOf(info.versionCode));
                        appInfo.setInstallTime(info.firstInstallTime);
                        appInfo.setMainActivity(info.mainActivity);
                        appInfo.setPackageName(info.pkgName);
                        // if (!info.mainActivity.equals(AppStoreActivity.class.getName()))
                        ret.add(appInfo);
                    }
                }
            }
        }
        return ret;
    }

    private List<AppInfo> getInstalledApps() {
        LiteURI uri = LiteURI.create("apps://com.coocaa.app/installed_apps");
        uri.addParams("filter", "mine");
        String json = null;
        try {
            json = LiteContentServiceConnecter.getService().call(uri.toString());
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        List<AppInfo> appList = new ArrayList<AppInfo>();
        try {
            if (json != null) {
                RP_Installed_Apps rp = RP_Installed_Apps.parseJObject(json, RP_Installed_Apps.class);
                List<AppData> appdatas = rp.resource.resource_items;
                if (appdatas != null && appdatas.size() > 0) {
                    for (AppData appdata : appdatas)
                        appList.add(appdata.info);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return appList;
    }

    private void refreshMainContent() {
        List<AppInfo> appList = getInstalledApps();
        LogUtils.d("localapp", "refreshMainContent size:" + appList.size());
        final List<SkyAppBaseData> appDataLists = formData(appList);
//        runOnUiThread(new Runnable() {
//            public void run() {
        if (mContentListener != null)
            mContentListener.refreshContent(appDataLists, getCategoryData(MINE));
        refreshMyAppCorner(appDataLists);
//            }
//        });
    }


    private SkyCategoryData getCategoryData(String id) {
        if (id.equals(MINE))
            return new SkyCategoryData(MINE, getString(R.string.main_mine));
        else if (id.equals(GUANLI))
            return new SkyCategoryData(GUANLI, getString(R.string.main_manager));
        else
            return null;
    }

    @Override
    public void getCategoryContent(final OnContentRefreshListener listener,
                                   final SkyCategoryData category) {
        // TODO Auto-generated method stub
    }

    @Override
    public void getCategoryData(final OnCategoryRefreshListener listener) {
        // TODO Auto-generated method stub
        LogUtils.d(tag, "getCategoryData----");
        LogUtils.d("mytime", "Calling getCategoryData");
        // 从数据库拿数据
        if (!AppStoreBaseController.NETSTATUS) {
            List<SkyCategoryData> categoryData = AppStoreDB.getInstance().getCategoryData();
            categoryData.add(0, new SkyCategoryData(MINE, getString(R.string.main_mine)));
            categoryData.add(new SkyCategoryData(GUANLI, getString(R.string.main_manager)));
            // firstSortList = categoryData;
            listener.refreshCategory(categoryData);
            return;
        }
        if (mainPageList != null && mainPageList.size() > 0) {
            List<SkyCategoryData> categoryData = getMainCategoryList();
            listener.refreshCategory(categoryData);
            return;
        }
        new Thread() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                int time = 0;
                int delayTime = 10000;
                List<SkyCategoryData> categoryData = AppStoreDB.getInstance().getCategoryData();
                if (categoryData.size() != 0) {
                    delayTime = 0;
                }
                boolean needFresh = true;
                while (mainPageList == null || mainPageList.size() == 0) {
                    try {
                        Thread.currentThread().sleep(200);
                        time += 200;
                        if (time >= delayTime && needFresh) {
                            LogUtils.d("test", "getCategoryData---time >= delayTime----");
                            categoryData.add(new SkyCategoryData(GUANLI,
                                    getString(R.string.main_manager)));
                            categoryData.add(0, new SkyCategoryData(MINE,
                                    getString(R.string.main_mine)));
                            LogUtils.d("localapp", "categoryData  size:" + categoryData.size());
                            listener.refreshCategory(categoryData);
                            mLocalData = true;
                            needFresh = false;
                            // return;
                        }
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                time = 0;
                List<SkyCategoryData> categoryData2 = getMainCategoryList();
                // LogUtils.d("localapp",
                // "categoryData2  size:"+categoryData2.size()+" size:"+categoryData.size());
                boolean flag = false;
                if (categoryData2.size() == categoryData.size()) {
                    int size = categoryData2.size();
                    for (int i = 0; i < size; i++) {
                        // LogUtils.d("localapp",
                        // "id:"+categoryData2.get(i).id+" "+categoryData.get(i).id);
                        if (!categoryData2.get(i).id.trim().equals(categoryData.get(i).id.trim())) {
                            flag = true;
                            break;
                        }
                    }
                } else {
                    flag = true;
                }
                LogUtils.d("test", "flag:" + flag);
                if (flag)
                    listener.refreshCategory(categoryData2);
            }
        }.start();
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        CoocaaApplication.removePackageListener(this);
        AppStoreBaseController.removeUpdateDownloadCountHandler(mUpdateDownloadCountHandler);
        Storage.removeListener(mainPageController);
        LiteAppApplication.removeContentAppChangedReceiverListener(this);
        mContentListener = new OnContentRefreshListener(){
            @Override
            public void refreshContent(List<SkyAppBaseData> appDataLists, SkyCategoryData categoryData) {

            }

            @Override
            public void refreshCategory(List<SkyCategoryData> categoryDatas) {

            }

            @Override
            public void refreshCategoryRed(SkyCategoryData data, int num) {

            }

            @Override
            public void refreshScategoryRed(SkyCategoryData categoryData, SkyAppBaseData data, int num) {

            }

            @Override
            public void refreshMyAppCorner(SkyListAppData data) {

            }

            @Override
            public void onAppStatusChanged(String pkg, AppStatus status) {

            }
        };
        myAppLoaded = false;
    }

    private void refreshStatus(String pkg, AppStatus status) {
        LogUtils.d("test", "refreshStatus  pkg:" + pkg + " status:" + status + " " + (mContentListener != null));
        if (mContentListener != null)
            mContentListener.onAppStatusChanged(pkg, status);   //更新的回调
    }

    @Override
    public void installEvent(Intent i) {
        // TODO Auto-generated method stub
        LogUtils.d("test", "MainPage  install-----");
        String pkg = i.getData().getSchemeSpecificPart();
        if (pkg.equals(AppStoreApplication.FANS_APK_PKG))
        {
            LogUtils.d("install", "MainPage  install---need kill self--");
            AppStoreApplication.needKillApplication = true;
        } else
        {
        }
        refreshStatus(pkg, AppStatus.INSTALLED);
    }

    @Override
    public void uninstallEvent(Intent i) {
        // TODO Auto-generated method stub
        LogUtils.d("test", "MainPage  uninstall-----");
        String pkg = i.getData().getSchemeSpecificPart();
        refreshStatus(pkg, AppStatus.NOT_DOWNLOADED);
    }

    @Override
    public void getLocalCategoryData(OnCategoryRefreshListener listener) {
        // TODO Auto-generated method stub
        LogUtils.d(tag, "getLocalCategoryData----");
        List<SkyCategoryData> localFirstSortList = new ArrayList<SkyCategoryData>();
        localFirstSortList.add(new SkyCategoryData(MINE, getString(R.string.main_mine)));
        listener.refreshCategory(localFirstSortList);
    }

    @Override
    public void refreshCagegoryContent(SkyCategoryData category) {
        if (mLocalData && mainPageList != null && mainPageList.size() > 0
                && !mHashRefresh.contains(category)) {
            List<SkyAppBaseData> appDataLists = getAppDataList(category);
            LogUtils.d(tag, "getCategoryContent--(appDataLists != null)--" + (appDataLists != null));
            mContentListener.refreshContent(appDataLists, category);
            mHashRefresh.add(category);
        }
    }

    @Override
    public void onStorageMounted(SDevice device) {
        // TODO Auto-generated method stub
        LogUtils.d(tag, "onStorageMounted  devices:" + device.getMediaType());
        if (device.getMediaType() == SDevice.MEDIA_TYPE.SDCARD) {
            LogUtils.d(tag, "onStorageMounted  sdcard!!!"+managerList.size());
            if(managerList.size() < 1)
                return;
            synchronized (managerList) {
                managerList.clear();
            }
            refreshGLContent(GUANLI);
        }
    }

    @Override
    public void onStorageRemoved(SDevice device) {
        // TODO Auto-generated method stub
        LogUtils.d(tag, "onStorageRemoved  devices:" + device.getMediaType());
        if (device.getMediaType() == SDevice.MEDIA_TYPE.SDCARD) {
            LogUtils.d(tag, "onStorageRemoved  sdcard!!!"+managerList.size());
            if(managerList.size() < 1)
                return;
            synchronized (managerList) {
                managerList.clear();
            }
            refreshGLContent(GUANLI);
        }
    }

    @Override
    public void onAction(Intent i) {
        runOnThread(new Runnable() {
            @Override
            public void run() {
                refreshMainContent();
            }
        });
        String[] pkgArray = null;
        if (i != null)
            pkgArray = i.getStringArrayExtra("extra");
        if (pkgArray != null && pkgArray.length > 0) {
            LogUtils.d(tag, "onAction  pkg:" + pkgArray.length);
            for (String pkg : pkgArray) {
                refreshUpdateBlock(pkg);
                if (pkg != null && !pkg.equals("")) {
                    AppStatus status = AppStatus.NOT_DOWNLOADED;
                    status = AppDataProvider.getInstance().isAppInstalled(pkg);
                    refreshStatus(pkg, status);
                }
            }
        }
    }
}
